package controllers

import (
	"encoding/json"
	"strconv"
	"strings"

	"github.com/beego/beego/v2/client/orm"
	"github.com/beego/beego/v2/core/logs"
	"github.com/beego/beego/v2/server/web"

	"supershare/backend/middleware"
	"supershare/backend/models"
)

// MiniprogramBannerController 小程序轮播图控制器
type MiniprogramBannerController struct {
	web.Controller
}

// Get 获取轮播图列表
// @Title Get
// @Description 获取轮播图列表
// @Param page query int false "页码"
// @Param pageSize query int false "每页数量"
// @Param title query string false "标题"
// @Param type query int false "类型"
// @Param status query int false "状态"
// @Success 200 {object} models.Response
// @Failure 500 服务器错误
// @router / [get]
func (c *MiniprogramBannerController) Get() {
	// 获取分页参数
	page, _ := c.GetInt("page", 1)
	pageSize, _ := c.GetInt("pageSize", 10)

	// 获取过滤条件
	filters := make(map[string]interface{})
	if title := c.GetString("title"); title != "" {
		filters["title"] = title
	}
	if bannerType, err := c.GetInt8("type"); err == nil {
		filters["type"] = bannerType
	}
	if status, err := c.GetInt8("status"); err == nil {
		filters["status"] = status
	}
	admin, _ := middleware.GetCurrentAdmin(c.Ctx)
	if admin == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "参数错误",
			"error":   "没有权限",
		}
		c.ServeJSON()
		return
	}
	if admin.FranchiseId > 0 {
		filters["franchise_id"] = admin.FranchiseId
	}
	// 获取轮播图列表
	banners, total, err := models.GetBannerList(page, pageSize, filters)
	if err != nil {
		logs.Error("获取轮播图列表失败: %v", err)
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取轮播图列表失败",
			"error":   err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取轮播图列表成功",
		"data": map[string]interface{}{
			"list":     banners,
			"total":    total,
			"page":     page,
			"pageSize": pageSize,
		},
	}
	c.ServeJSON()
}

// GetOne 获取单个轮播图
// @Title GetOne
// @Description 获取单个轮播图
// @Param id path int true "轮播图ID"
// @Success 200 {object} models.Response
// @Failure 500 服务器错误
// @router /:id [get]
func (c *MiniprogramBannerController) GetOne() {
	// 获取轮播图ID
	idStr := c.Ctx.Input.Param(":id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "参数错误",
			"error":   err.Error(),
		}
		c.ServeJSON()
		return
	}

	admin, _ := middleware.GetCurrentAdmin(c.Ctx)
	if admin == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "参数错误",
			"error":   "没有权限",
		}
		c.ServeJSON()
		return
	}
	// 获取轮播图
	banner, err := models.GetBannerById(id)
	if err != nil {
		logs.Error("获取轮播图失败: %v", err)
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取轮播图失败",
			"error":   err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取轮播图成功",
		"data":    banner,
	}
	c.ServeJSON()
}

// Post 创建轮播图
// @Title Post
// @Description 创建轮播图
// @Param body body models.Banner true "轮播图信息"
// @Success 200 {object} models.Response
// @Failure 500 服务器错误
// @router / [post]
func (c *MiniprogramBannerController) Post() {
	// 解析请求参数
	var banner models.Banner
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &banner)
	if err != nil {
		logs.Error("解析请求参数失败: %v", err)
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "参数错误",
			"error":   err.Error(),
		}
		c.ServeJSON()
		return
	}

	admin, _ := middleware.GetCurrentAdmin(c.Ctx)
	if admin == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "参数错误",
			"error":   "没有权限",
		}
		c.ServeJSON()
		return
	}
	banner.FranchiseId = admin.FranchiseId
	banner.BeforeInsert()
	banner.CreatedBy = admin.Username
	banner.UpdatedBy = admin.Username
	// 创建轮播图
	_, err = models.CreateBanner(&banner)
	if err != nil {
		logs.Error("创建轮播图失败: %v", err)
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "创建轮播图失败",
			"error":   err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "创建轮播图成功",
	}
	c.ServeJSON()
}

// Put 更新轮播图
// @Title Put
// @Description 更新轮播图
// @Param body body models.Banner true "轮播图信息"
// @Success 200 {object} models.Response
// @Failure 500 服务器错误
// @router / [put]
func (c *MiniprogramBannerController) Put() {
	// 解析请求参数
	var banner models.Banner
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &banner)
	if err != nil {
		logs.Error("解析请求参数失败: %v", err)
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "参数错误",
			"error":   err.Error(),
		}
		c.ServeJSON()
		return
	}

	admin, _ := middleware.GetCurrentAdmin(c.Ctx)
	if admin == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "参数错误",
			"error":   "没有权限",
		}
		c.ServeJSON()
		return
	}
	banner.UpdatedBy = admin.Username
	banner.BeforeUpdate()
	// 更新轮播图
	err = models.UpdateBanner(&banner, "Title", "ImageUrl", "LinkUrl", "LinkType", "Type", "Status", "SortOrder", "StartTime", "EndTime", "UpdatedBy", "UpdatedAt")
	if err != nil {
		logs.Error("更新轮播图失败: %v", err)
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "更新轮播图失败",
			"error":   err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "更新轮播图成功",
	}
	c.ServeJSON()
}

// Delete 删除轮播图
// @Title Delete
// @Description 删除轮播图
// @Param id path int true "轮播图ID"
// @Success 200 {object} models.Response
// @Failure 500 服务器错误
// @router /:id [delete]
func (c *MiniprogramBannerController) Delete() {
	// 获取轮播图ID
	idStr := c.Ctx.Input.Param(":id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "参数错误",
			"error":   err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 删除轮播图
	err = models.DeleteBanner(id)
	if err != nil {
		logs.Error("删除轮播图失败: %v", err)
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "删除轮播图失败",
			"error":   err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "删除轮播图成功",
	}
	c.ServeJSON()
}

// UpdateSort 更新轮播图排序
// @Title UpdateSort
// @Description 更新轮播图排序
// @Param body body []models.Banner true "轮播图排序信息"
// @Success 200 {object} models.Response
// @Failure 500 服务器错误
// @router /sort [put]
func (c *MiniprogramBannerController) UpdateSort() {
	// 解析请求参数
	var banners []models.Banner
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &banners)
	if err != nil {
		logs.Error("解析请求参数失败: %v", err)
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "参数错误",
			"error":   err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 更新排序
	o := orm.NewOrm()
	tx, err := o.Begin()
	if err != nil {
		logs.Error("开启事务失败: %v", err)
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "更新排序失败",
			"error":   err.Error(),
		}
		c.ServeJSON()
		return
	}

	for _, banner := range banners {
		_, err = o.Update(&banner, "SortOrder")
		if err != nil {
			tx.Rollback()
			logs.Error("更新排序失败: %v", err)
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "更新排序失败",
				"error":   err.Error(),
			}
			c.ServeJSON()
			return
		}
	}

	err = tx.Commit()
	if err != nil {
		tx.Rollback()
		logs.Error("提交事务失败: %v", err)
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "更新排序失败",
			"error":   err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "更新排序成功",
	}
	c.ServeJSON()
}

// GetPublicList 获取公开的轮播图列表 (供小程序前端使用)
func (c *MiniprogramBannerController) GetPublicList() {
	// 直接查询所有启用的轮播图
	banners, err := models.GetActiveBanners(0)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取轮播图失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 基础URL
	baseURL := web.AppConfig.DefaultString("imghost", "http://127.0.0.1:8888")

	// 转换为前端所需数据格式
	var bannerList []map[string]interface{}
	for _, banner := range banners {
		// 处理图片URL，如果不是以http开头，则添加基础URL
		imageUrl := banner.ImageUrl
		if len(imageUrl) > 0 && imageUrl[0] == '/' {
			imageUrl = baseURL + strings.ReplaceAll(imageUrl, "\\", "/")
		}

		bannerList = append(bannerList, map[string]interface{}{
			"id":       banner.Id,
			"imageUrl": imageUrl,
			"linkUrl":  banner.LinkUrl,
			"title":    banner.Title,
		})
	}

	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取轮播图成功",
		"data": map[string]interface{}{
			"list": bannerList,
		},
	}
	c.ServeJSON()
}
